package com.patrol.patrol.ui.appear;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.patrol.patrol.MyApplication;
import com.patrol.patrol.R;
import com.patrol.patrol.data.EventImgModel;
import com.patrol.patrol.data.EventModel;
import com.patrol.patrol.data.KeyValueInfo;
import com.patrol.patrol.ui.BaseFragment;
import com.patrol.patrol.utils.ToastUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhaoss.weixinrecorded.activity.RecordedActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

public class AppearFragment extends BaseFragment {

    Unbinder unbinder;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_num)
    EditText etNum;
//    @BindView(R.id.et_school)
//    EditText etSchool;
    @BindView(R.id.sp_sex)
    Spinner spSex;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.grid_exp)
    ExpandableGridView gridExp;
    @BindView(R.id.img_camera)
    ImageView imgCamera;
    @BindView(R.id.tv_update)
    TextView tvUpdate;

    ImageAdapter adapter;
    List<ImageInfo> imageInfos;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setContentView(R.layout.fragment_appear);
        unbinder = ButterKnife.bind(this, getContentView());

        ArrayAdapter<KeyValueInfo> arrayAdapter = new ArrayAdapter<KeyValueInfo>(getContext(), android.R.layout.simple_spinner_dropdown_item, AppearActivity.spSexDataList);
        spSex.setAdapter(arrayAdapter);

        imageInfos = new ArrayList<>();
        adapter = new ImageAdapter(imageInfos, getContext(), new ImageAdapter.OnItemDeleteClick() {
            @Override
            public void onItemDeleteClick(int position) {
                imageInfos.remove(position);
                adapter.notifyDataSetChanged();
            }
        }, new ImageAdapter.OnItemClick() {
            @Override
            public void onItemClick(int position) {

            }
        });
        gridExp.setAdapter(adapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.img_camera, R.id.tv_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_camera:
                AndPermission.with(getActivity()).permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .requestCode(0).callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        Intent intent = new Intent(getContext(), RecordedActivity.class);
                        startActivityForResult(intent, 1);
                    }
                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    }
                }).start();
                break;
            case R.id.tv_update:
                EventModel model = new EventModel();
                model.setEtName(etName.getText().toString())
                        .setEtNum(etNum.getText().toString())
//                        .setEtSchool(etSchool.getText().toString())
                        .setSpSex(((KeyValueInfo)(spSex.getSelectedItem())).getKey())
                        .setEtRemark(etRemark.getText().toString())
                        .setTime(System.currentTimeMillis()/1000);
                MyApplication.dbProxy.insert(model);

                if(null != imageInfos && imageInfos.size()>0){
                    List<EventImgModel> imgModelList = new ArrayList<>();
                    for(ImageInfo imageInfo:imageInfos){
                        EventImgModel imgModel = new EventImgModel();
                        imgModel.setEventId(model.getPrimaryKey());
                        imgModel.setImageType(imageInfo.getImageType());
                        imgModel.setImageUrl(imageInfo.getImageUrl());
                        imgModelList.add(imgModel);
                    }
                    MyApplication.dbProxy.insert(imgModelList);
                }

                ToastUtils.showToast(model.getPrimaryKey()+"");
                etName.setText("");
                etNum.setText("");
//                etSchool.setText("");
                etRemark.setText("");
                imageInfos.clear();
                adapter.notifyDataSetChanged();
                ViewPager viewPager = ((TabActivity)getActivity()).mViewPager;
                viewPager.setCurrentItem(1,true);
                ListFragment listFragment = (ListFragment) ((PagerAdapter)viewPager.getAdapter()).getItem(1);
                List<EventModel> modelList = MyApplication.dbProxy.queryListBySql(EventModel.class,"select * from event_model");
                listFragment.equipListAdapter.modelList.clear();
                listFragment.equipListAdapter.modelList.addAll(modelList);
                listFragment.equipListAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==RESULT_OK && data!=null){
            if(requestCode == 1){
//                textureView.setVisibility(View.GONE);
//                iv_photo.setVisibility(View.GONE);
                int dataType = data.getIntExtra(RecordedActivity.INTENT_DATA_TYPE, RecordedActivity.RESULT_TYPE_VIDEO);
                if(dataType == RecordedActivity.RESULT_TYPE_VIDEO){
                    String videoPath = data.getStringExtra(RecordedActivity.INTENT_PATH);
//                    tv_path.setText("视频地址: "+videoPath);
//                    textureView.setVisibility(View.VISIBLE);
//                    playVideo(videoPath);
                    imageInfos.add(new ImageInfo().setImageUrl(videoPath).setImageType(RecordedActivity.RESULT_TYPE_VIDEO));
                }else if(dataType == RecordedActivity.RESULT_TYPE_PHOTO){
                    String photoPath = data.getStringExtra(RecordedActivity.INTENT_PATH);
//                    tv_path.setText("图片地址: "+photoPath);
//                    iv_photo.setVisibility(View.VISIBLE);
//                    iv_photo.setImageBitmap(BitmapFactory.decodeFile(photoPath));
                    imageInfos.add(new ImageInfo().setImageUrl(photoPath).setImageType(RecordedActivity.RESULT_TYPE_PHOTO));
                }

                adapter.notifyDataSetChanged();
            }
        }
    }
}
